﻿using Microsoft.AspNetCore.Mvc.Formatters;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace RemoteSensingImageDirectServer.Register.XML
{
    public class XmlOutputFormatter : XmlSerializerOutputFormatter
    {
        public XmlOutputFormatter(XmlWriterSettings writerSettings) : base(writerSettings) { }

        public override XmlWriter CreateXmlWriter(TextWriter writer, XmlWriterSettings xmlWriterSettings)
        {
            var xmlWriter = base.CreateXmlWriter(writer, xmlWriterSettings);
            return xmlWriter;
        }

        public override XmlWriter CreateXmlWriter(OutputFormatterWriteContext context, TextWriter writer, XmlWriterSettings xmlWriterSettings)
        {
            var xmlWriter = base.CreateXmlWriter(context, writer, xmlWriterSettings);
            return xmlWriter;
        }

        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var response = context.HttpContext.Response;
            if (context.Object is XmlDocument)
            {
                XmlDocument doc = (XmlDocument)context.Object;
                MemoryStream stream = new MemoryStream();
                XmlTextWriter writer = new XmlTextWriter(stream, selectedEncoding);
                writer.Formatting = Formatting.Indented;
                doc.Save(writer);

                StreamReader reader = new StreamReader(stream, selectedEncoding);
                stream.Position = 0;
                string content = reader.ReadToEnd();
                content = content.Replace("[]", "");
                reader.Close();
                stream.Close();
                response.ContentType = "application/xml";
                return response.WriteAsync(content);
            }
            else
            {
                return base.WriteResponseBodyAsync(context, selectedEncoding);
            }
        }

        protected override bool CanWriteType(Type type)
        {
            return type == typeof(string) ? false : base.CanWriteType(type);
        }

        protected override XmlSerializer CreateSerializer(Type type)
        {
            return base.CreateSerializer(type);
        }

        protected override Type GetSerializableType(Type type)
        {
            return base.GetSerializableType(type);
        }

        protected override void Serialize(XmlSerializer xmlSerializer, XmlWriter xmlWriter, object value)
        {
            base.Serialize(xmlSerializer, xmlWriter, value);

        }
    }
}
